Learn R Programming

rTorch (version 0.4.2)

[.torch.Tensor: Subset tensors with [

Description

Subset tensors with [

Usage

# S3 method for torch.Tensor
[(
  x,
  ...,
  drop = TRUE,
  style = getOption("torch.extract.style"),
  options = torch_extract_opts(style)
)

Arguments

x

a tensor

...

slicing specs. See examples and details.

drop

whether to drop scalar dimensions

style

One of "python" or "R".

options

An object returned by torch_extract_opts()

Examples

Run this code
# NOT RUN {
x <- torch$arange(0L, 15L)$view(3L, 5L)

# by default, numerics supplied to `...` are interpreted R style
x[,1]    # first column
x[1:2,]  # first two rows
x[,1, drop = FALSE]

# strided steps can be specified in R syntax or python syntax
x[, seq(1, 5, by = 2)]
x[, 1:5:2]

# if you are unfamiliar with python-style strided steps, see:
# https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#basic-slicing-and-indexing

# missing arguments for python syntax are valid, but they must by backticked
# or supplied as NULL
x[, `::2`]
x[, NULL:NULL:2]
x[, `2:`]

# Another Python feature that is available is a Python style ellipsis `...`
# (not to be confused with R dots `...`), that in R has been defined as
# all_dims() expands to the shape of the tensor

y <- torch$arange(0L, 3L^5L)$view(3L, 3L, 3L, 3L, 3L)
as.logical((all(y[all_dims(), 1] == y[,,,,1]))$numpy()) == TRUE


# negative numbers are always interpreted Python style
# The first time a negative number is supplied to `[`, a warning is issued
# about the non-standard behavior.
x[-1,] # last row, with a warning
x[-1,] # the warning is only issued once

# specifying `style = 'python'` changes the following:
# +  zero-based indexing is used
# +  slice sequences in the form of `start:stop` do not include `stop`
#    in the returned value
# +  out-of-bounds indices in a slice are valid

# The style argument can be supplied to individual calls of `[` or set
# as a global option

# example of zero based  indexing
x[0, , style = 'python']   # first row
x[1, , style = 'python']   # second row

# example of slices with exclusive stop
# run the next options() line before the tensor operations

options(torch.extract.style = 'python')
x[, 0:1]   # just the first column
x[, 0:2]   # first and second column

# example of out-of-bounds index
x[, 0:10]
options(torch.extract.style = NULL)

# slicing with tensors is valid too, but note that tensors are never
# translated and are always interpreted Python-style.
# A warning is issued the first time a tensor is passed to `[`
# just as in Python, only scalar tensors are valid

# To silence the warnings about tensors being passed as-is and negative numbers
# being interpreted python-style, set
options(torch.extract.style = 'R')

# clean up from examples
options(torch.extract.style = NULL)
# }

Run the code above in your browser using DataLab